package com.shushan.login;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.db.ChildBeanDao;
import com.shushan.db.ChildBookDao;
import com.shushan.home.TabHomeActivity;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.ChildBookBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.setting.BookSelectActivity;
import com.shushan.setting.ChildSettingActivity;
import com.shushan.setting.ParentPswSetActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.util.VerifyTools;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * @ClassName: MobileBindActivity
 * @Desciption: 绑定手机号码
 * @author: yichaohua
 * @date: 2018-11-20
 */
public class MobileBindActivity extends BaseActivity implements TextWatcher, View.OnClickListener {

    private static final String TAG = "MobileBindActivity";

    private EditText mobileEdit;
    private EditText verCodeEdit;
    private ImageView delImg;
    private Button verCodeButton;
    private Button submitButton;

    private String openId;
    private String msgId = "";
    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.mobile_bind_activity);

        ScreenManager sm = new ScreenManager();
        sm.setStatusBar(true, this);

        openId = getIntent().getStringExtra("openId");
        Log.i(TAG,"openId=" + openId);

        initView();
    }

    private void initView() {
        mobileEdit = findViewById(R.id.et_phone_num);
        mobileEdit.addTextChangedListener(this);
        delImg = findViewById(R.id.mobile_bind_del_img);
        delImg.setOnClickListener(this);
        verCodeEdit = findViewById(R.id.ver_code_edit);
        verCodeButton = findViewById(R.id.mobile_bind_code_btn);
        verCodeButton.setOnClickListener(this);
        submitButton = findViewById(R.id.mobile_bind_submit_btn);
        submitButton.setOnClickListener(this);
    }



    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(count >= 1){
            delImg.setVisibility(View.VISIBLE);
        }else {
            delImg.setVisibility(View.GONE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mobile_bind_del_img:
                mobileEdit.setText("");
                break;
            case R.id.mobile_bind_code_btn:
                sendCode();
                break;
            case R.id.mobile_bind_submit_btn:
                if (valide()) {
                    bindMobile();
                }
                break;
            default:
                break;
        }
    }

    private boolean valide() {
        String mobile = mobileEdit.getText().toString();
        if(TextUtils.isEmpty(mobile)){
            showToast("请输入手机号码");
            return false;
        }

        String code = verCodeEdit.getText().toString();
        if(TextUtils.isEmpty(code)){
            showToast("请输入验证码");
            return false;
        }

        if (!StringTools.isMobile(mobile)) {
            showToast("手机号输入有误");
            return false;
        }

        if (TextUtils.isEmpty(msgId)) {
            showToast("验证码ID为空");
            return false;
        }

        return true;
    }

    private void sendCode() {
        String mobile = mobileEdit.getText().toString();
        if(TextUtils.isEmpty(mobile)){
            showToast("请输入手机号码");
            return;
        }

        if (!StringTools.isMobile(mobile)) {
            showToast("手机号输入有误");
            return;
        }

        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.SEND_VER_CODE);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("debug", BuildConfig.DEBUG ? 1 : 0)
                .putValue("phone", mobile);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        Log.i(TAG, "onSuccess data=" + data);

                        VerifyTools.getInstance().startVerifyWaiting(MobileBindActivity.this,verCodeButton);

                        String code = "";
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            msgId = jsonObject.optString("msgid", "");
                            code = jsonObject.optString("code", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (TextUtils.isEmpty(msgId)) {
                            showToast("验证码ID为空");
                            return;
                        }

                        if(BuildConfig.DEBUG){
                            showCodeDialog(code);
                        }else {
                            showToast("短信验证码发送成功");
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void bindMobile() {
        showWaitDialog();

        String mobile = mobileEdit.getText().toString();
        String code = verCodeEdit.getText().toString();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.BIND_THIRD_LOGIN);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("phone", mobile)
                .putValue("code", code)
                .putValue("msgid", msgId)
                .putValue("thirdid", openId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UserBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(UserBean userBean) {
                        if(userBean != null){
                            UmengEventUtil.onProfileSignIn(userBean.phone);

                            SharedPreferencesUtils.setBooleanDate(Constants.APP_NOT_FIRST_SHAREPREFERS_KEY,true);
                            SharedPreferencesUtils.setStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY,userBean.phone);
                            shuShanApplication.setUserBean(userBean);

                            SharedPreferencesUtils.setStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY,userBean.password);

                            final PushAgent mPushAgent = PushAgent.getInstance(MobileBindActivity.this);
                            int currentChildId = shuShanApplication.getCurrentChildId();
                            if(currentChildId > 0){
                                mPushAgent.setAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                                    @Override
                                    public void onMessage(boolean isSuccess, String message) {
                                        Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                                    }
                                });
                            }

                            int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
                            if(useId > 0){
                                mPushAgent.setAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                                    @Override
                                    public void onMessage(boolean isSuccess, String message) {
                                        Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                                    }
                                });
                            }

                            List<ChildBean> childList = userBean.getChildList();
                            if(childList.size() > 0){
                                new ChildBeanDao(shuShanApplication).dropAndAddList(childList);

                                ChildBean childBean = childList.get(0);
                                new ChildBookDao(shuShanApplication).clearTab();
                                if(ToolUtils.isListEmpty(childBean.getBookBeanList())){
                                    Intent intent = new Intent(MobileBindActivity.this,BookSelectActivity.class);
                                    intent.putExtra("gradeId",childBean.gradeId);
                                    intent.putExtra("semester",childBean.semester);
                                    intent.putExtra("firstTime",1);
                                    startActivityAllow(intent);

                                }else {
                                    List<ChildBookBean> bookBeanList = childBean.getBookBeanList();
                                    new ChildBookDao(shuShanApplication).addOrUpdateList(bookBeanList);

                                    if(!TextUtils.isEmpty(userBean.password)){
                                        SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,true);
                                        Intent intent = new Intent(MobileBindActivity.this,TabHomeActivity.class);
                                        intent.putExtra("firstTime",1);
                                        startActivityAllow(intent);
                                    }else {
                                        Intent intent = new Intent(MobileBindActivity.this,ParentPswSetActivity.class);
                                        intent.putExtra("firstTime",1);
                                        startActivityAllow(intent);
                                    }
                                }


                            }else {
                                new ChildBeanDao(shuShanApplication).clearTab();

                                Intent intent = new Intent(MobileBindActivity.this,ChildSettingActivity.class);
                                intent.putExtra("firstTime",1);
                                startActivityAllow(intent);
                            }
                        }

                        onBackAction();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void showCodeDialog(String code) {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("【书山宝】 验证码：" + code + ",书山用户，您正在使用手机账号登陆，请您在5分钟内完成验证。")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    }
}
